<template>
    <div class="content-box">
        <div class="vpn-container">
            <div class="page-header">
                <div class="page-tit">
                    设备列表
                </div>
            </div>

            <div class="user-l" v-loading="state.isLoading">
                <div class="item" v-for="(item, k) in state.tableData">
                    <div class="img">
                        <img :src="item.preview_img" alt="item.user_id" v-if="item.preview_img">
                        <div class="color-success" v-else>暂无预览图</div>
                    </div>
                    <div>
                        <div>用户：{{ item.user_id }}</div>
                        <div>屏幕：{{ item.screens ? item.screens.length: 0 }}个</div>
                        <div>远程：{{ item.control_flag ? `启用` : '禁用' }}</div>
                        <div>状态：{{ item.control_by ? `${item.control_by}正在使用` : '空闲' }}</div>
                    </div>
                    <div class="control">
                        <el-button type="primary" @click="startControl(item)" v-if="item.user_id !== state.userId && item.control_flag && !item.control_by">控制</el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import {inject, onMounted, onUnmounted, reactive, ref} from "vue";
import {webrtcUsersApi} from "../../api/api";

const state = reactive({
    tableData: [],
    isLoading: false,
    userId: window.APP_CONFIG.user_id,
});

let timer = null;

const startClient = inject('startClient')

const startControl = (item) => {
    startClient(item);
}

// 拉取电脑列表
const getList = () => {
    webrtcUsersApi().then(res => {
        state.isLoading = false;
        if (res.code === 0) {
            state.tableData = res.records;
        }
    })
}

// 组件挂载时自动连接
onMounted(async () => {
    state.isLoading = true;
    setTimeout(function (){
        getList()
    }, 3000)

    if (!timer) {
        timer = setInterval(() => {
            getList()
        }, 10000);
    }
})

// 组件卸载时断开连接
onUnmounted(() => {
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
})
</script>